package base.utils;

import java.lang.reflect.Field;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import base.application.BaseApplication;

/**
 * System utils
 * 
 * @author Administrator
 * 
 */
public class SystemUtils {

	public static int VERSION_CODE = android.os.Build.VERSION.SDK_INT;

	/**
	 * @see <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels">Api level code to int</a>
	 * @return
	 */
	public static int getSystemApiLevelInt() {
		return VERSION_CODE;
	}

	/**
	 * 
	 * @param vCodeShowable
	 * @return
	 */
	public static String getVersion(boolean vCodeShowable) {
		String version = "";
		try {
			PackageInfo pi = BaseApplication.getInstance().getPackageManager().getPackageInfo(BaseApplication.getInstance().getPackageName(), 0);
			version = pi.versionName + (vCodeShowable ? ("." + pi.versionCode) : "");
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return version;
	}

	public static String getMd5Hash(String origin) {
		String resultString = null;
		if (origin == null) {
			throw new IllegalArgumentException("input");
		}
		try {
			byte[] input = origin.getBytes();
			if (input == null) {
				throw new IllegalArgumentException("input");
			}
			try {
				MessageDigest md = MessageDigest.getInstance("MD5");
				byte[] messageDigest = md.digest(input);
				BigInteger number = new BigInteger(1, messageDigest);
				String md5 = getPaddedString(number.toString(16), 32);
				resultString = md5;
			} catch (NoSuchAlgorithmException e) {
				return null;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return resultString;
	}

	public static final String getPaddedString(String str, int minLen) {
		if (str == null)
			str = "";
		StringBuilder buff = new StringBuilder(minLen);
		for (int n = 0, len = minLen - str.length(); n < len; n++) {
			buff.append('0');
		}
		buff.append(str);
		return buff.toString();
	}

	/**
	 * Whether wifi is on or not .
	 * 
	 * @return
	 */
	public static boolean checkWifiState() {
		ConnectivityManager cm = (ConnectivityManager) BaseApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifoInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		return wifoInfo != null && wifoInfo.isAvailable();
	}

	public static void showKeyBoard(EditText editText) {
		if (editText == null) {
			return;
		}
		InputMethodManager inputMethodManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.showSoftInput(editText, InputMethodManager.RESULT_SHOWN);
		inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
	}

	public static void hideKeyBoard(EditText editText) {
		if (editText == null) {
			return;
		}
		InputMethodManager inputMethodManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}

	/**
	 * Demo for get time !!
	 */
	public static void demoGettingTime() {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
	}

	/**
	 * Setting View's TextFont
	 * 
	 * @param view
	 * @param assetsPath
	 */
	public static void setTextFontAve(View view, String assetsPath) {
		if (view == null || TextUtils.isEmpty(assetsPath)) {
			return;
		}
		Typeface face = Typeface.createFromAsset(view.getContext().getAssets(), assetsPath);
		if (view instanceof TextView) {
			((TextView) view).setTypeface(face);
		} else if (view instanceof Button) {
			((Button) view).setTypeface(face);
		} else if (view instanceof EditText) {
			((EditText) view).setTypeface(face);
		} else {
			throw new IllegalArgumentException("View can not be set front !");
		}
	}

	private static long mLastBackClickTime = 0;
	private static final int BACK_SCALE = 2000;

	/**
	 * Double click close app.
	 * 
	 * @param toastRes
	 * @return
	 */
	public static boolean doubleBackCloseApp(int toastRes) {
		if (System.currentTimeMillis() - mLastBackClickTime > BACK_SCALE) {
			mLastBackClickTime = System.currentTimeMillis();
			if (toastRes > 0) {
				BaseApplication.showToast(toastRes);
			} else {
				BaseApplication.showToast("Click again to exit app");
			}
			return false;
		} else {
			mLastBackClickTime = System.currentTimeMillis();
			return true;
		}
	}

	/**
	 * 绠�崟瀵硅薄闂村睘鎬т竴鑷存椂鐨勫�鎷疯礉
	 * 
	 * @param from
	 * @param to
	 */
	public static void copy(Object from, Object to) {
		// Logger.debug(TAG, "copy from -> "+from +" to -> "+to);
		try {
			Field[] field = from.getClass().getDeclaredFields();
			for (int i = 0; i < field.length; i++) {
				try {
					Field f = field[i];
					f.setAccessible(true);
					f.set(to, f.get(from));
					f.setAccessible(false);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static StringBuilder getDevInfoBrief() {
		TelephonyManager tm = (TelephonyManager) BaseApplication.getInstance().getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
		StringBuilder sb = new StringBuilder();
		sb.append("#DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion());
		sb.append("\n#NetworkCountryIso = " + tm.getNetworkCountryIso());
		sb.append("\n#NetworkOperator = " + tm.getNetworkOperator());
		sb.append("\n#NetworkOperatorName = " + tm.getNetworkOperatorName());
		sb.append("\n#NetworkType = " + tm.getNetworkType());
		sb.append("\n#PhoneType = " + tm.getPhoneType());
		return sb;
	}

	public static String getDevInfo() {
		TelephonyManager tm = (TelephonyManager) BaseApplication.getInstance().getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
		StringBuilder sb = new StringBuilder();
		sb.append("\nDeviceId(IMEI) = " + tm.getDeviceId());
		sb.append("\nDeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion());
		sb.append("\nLine1Number = " + tm.getLine1Number());
		sb.append("\nNetworkCountryIso = " + tm.getNetworkCountryIso());
		sb.append("\nNetworkOperator = " + tm.getNetworkOperator());
		sb.append("\nNetworkOperatorName = " + tm.getNetworkOperatorName());
		sb.append("\nNetworkType = " + tm.getNetworkType());
		sb.append("\nPhoneType = " + tm.getPhoneType());
		sb.append("\nSimCountryIso = " + tm.getSimCountryIso());
		sb.append("\nSimOperator = " + tm.getSimOperator());
		sb.append("\nSimOperatorName = " + tm.getSimOperatorName());
		sb.append("\nSimSerialNumber = " + tm.getSimSerialNumber());
		sb.append("\nSimState = " + tm.getSimState());
		sb.append("\nSubscriberId(IMSI) = " + tm.getSubscriberId());
		sb.append("\nVoiceMailNumber = " + tm.getVoiceMailNumber());
		return sb.toString();
	}

}
